package org.jeecg.modules.lab.exam.question.controller;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jeecg.modules.lab.exam.bankQuestion.service.ILabExamBankQuestionService;
import org.jeecg.modules.lab.exam.entity.LabExamBankQuestion;
import org.jeecg.modules.lab.exam.entity.LabExamQuestion;
import org.jeecg.modules.lab.exam.entity.LabExamQuestionAnswer;
import org.jeecg.modules.lab.exam.question.service.ILabExamQuestionAnswerService;
import org.jeecg.modules.lab.exam.question.service.ILabExamQuestionService;
import org.jeecg.modules.lab.exam.question.vo.LabExamQuestionPage;
import org.jeecg.modules.lab.items.entity.LabItems;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;


 /**
 * @Description: 考试试题信息表
 * @Author: jeecg-boot
 * @Date:   2023-08-24
 * @Version: V1.0
 */
@Api(tags="考试试题信息表")
@RestController
@RequestMapping("/question/labExamQuestion")
@Slf4j
public class LabExamQuestionController {
	@Autowired
	private ILabExamQuestionService labExamQuestionService;
	@Autowired
	private ILabExamQuestionAnswerService labExamQuestionAnswerService;
	@Autowired
	private ILabExamBankQuestionService labExamBankQuestionService;

	/**
	 * 分页列表查询
	 *
	 * @param labExamQuestion
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "考试试题信息表-分页列表查询")
	@ApiOperation(value="考试试题信息表-分页列表查询", notes="考试试题信息表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<LabExamQuestion>> queryPageList(LabExamQuestion labExamQuestion,
														@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
														@RequestParam(name="pageSize", defaultValue="50") Integer pageSize,
														HttpServletRequest req) {
		QueryWrapper<LabExamQuestion> queryWrapper = QueryGenerator.initQueryWrapper(labExamQuestion, req.getParameterMap());
		Page<LabExamQuestion> page = new Page<LabExamQuestion>(pageNo, pageSize);
		IPage<LabExamQuestion> pageList = labExamQuestionService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param labExamQuestionPage
	 * @return
	 */
	@AutoLog(value = "考试试题信息表-添加")
	@ApiOperation(value="考试试题信息表-添加", notes="考试试题信息表-添加")
//    @RequiresPermissions("question:lab_exam_question:add")
	@ResponseBody
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody LabExamQuestionPage labExamQuestionPage) {
		LabExamQuestion labExamQuestion = new LabExamQuestion();
		BeanUtils.copyProperties(labExamQuestionPage, labExamQuestion);
		labExamQuestionService.saveMain(labExamQuestion, labExamQuestionPage.getLabExamQuestionAnswerList());
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param labExamQuestionPage
	 * @return
	 */
	@AutoLog(value = "考试试题信息表-编辑")
	@ApiOperation(value="考试试题信息表-编辑", notes="考试试题信息表-编辑")
//    @RequiresPermissions("question:lab_exam_question:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody LabExamQuestionPage labExamQuestionPage) {
		LabExamQuestion labExamQuestion = new LabExamQuestion();
		BeanUtils.copyProperties(labExamQuestionPage, labExamQuestion);
		LabExamQuestion labExamQuestionEntity = labExamQuestionService.getById(labExamQuestion.getId());
		if(labExamQuestionEntity==null) {
			return Result.error("未找到对应数据");
		}
		labExamQuestionService.updateMain(labExamQuestion, labExamQuestionPage.getLabExamQuestionAnswerList());
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "考试试题信息表-通过id删除")
	@ApiOperation(value="考试试题信息表-通过id删除", notes="考试试题信息表-通过id删除")
//    @RequiresPermissions("question:lab_exam_question:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		labExamQuestionService.delMain(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "考试试题信息表-批量删除")
	@ApiOperation(value="考试试题信息表-批量删除", notes="考试试题信息表-批量删除")
//    @RequiresPermissions("question:lab_exam_question:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.labExamQuestionService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}


	 /**
	  *  加入或移除题库
	  *
	  * @param ids
	  * @return
	  */
	 @AutoLog(value = "考试试题信息表-加入或移除题库")
	 @ApiOperation(value="考试试题信息表-加入或移除题库", notes="考试试题信息表-加入或移除题库")
	 @DeleteMapping(value = "/addOrDelBank")
	 public Result<String> addOrDelBank(@RequestParam(name="ids",required=true) String ids,
										@RequestParam(name="bId",required=true) String bId,
										@RequestParam(name="oper",required=true) String oper) {

		 if(oper.equals("add")){
			 this.labExamQuestionService.delBatchBank(ids,bId);
			 ArrayList listIds=new ArrayList(Arrays.asList(ids.split(",")));
			 Iterator<String> iterator = listIds.iterator();
			 while (iterator.hasNext()) {
				 String qId = iterator.next();
				 LabExamBankQuestion bankQuestion= new LabExamBankQuestion();
				 bankQuestion.setBankId(bId);
				 bankQuestion.setQuestionId(qId);
				 labExamBankQuestionService.save(bankQuestion);
			 }
			 return Result.OK("添加题库成功！");
		 }else {
			 this.labExamQuestionService.delBatchBank(ids,bId);
			 return Result.OK("移除题库成功！");
		 }
	 }
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "考试试题信息表-通过id查询")
	@ApiOperation(value="考试试题信息表-通过id查询", notes="考试试题信息表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<LabExamQuestion> queryById(@RequestParam(name="id",required=true) String id) {
		LabExamQuestion labExamQuestion = labExamQuestionService.getById(id);
		if(labExamQuestion==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(labExamQuestion);

	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "试题答案信息表通过主表ID查询")
	@ApiOperation(value="试题答案信息表主表ID查询", notes="试题答案信息表-通主表ID查询")
	@GetMapping(value = "/queryLabExamQuestionAnswerByMainId")
	public Result<List<LabExamQuestionAnswer>> queryLabExamQuestionAnswerListByMainId(@RequestParam(name="id",required=true) String id) {
		List<LabExamQuestionAnswer> labExamQuestionAnswerList = labExamQuestionAnswerService.selectByMainId(id);
		return Result.OK(labExamQuestionAnswerList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param labExamQuestion
    */
//    @RequiresPermissions("question:lab_exam_question:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, LabExamQuestion labExamQuestion) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<LabExamQuestion> queryWrapper = QueryGenerator.initQueryWrapper(labExamQuestion, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //配置选中数据查询条件
      String selections = request.getParameter("selections");
      if(oConvertUtils.isNotEmpty(selections)) {
         List<String> selectionList = Arrays.asList(selections.split(","));
         queryWrapper.in("id",selectionList);
      }
      //Step.2 获取导出数据
      List<LabExamQuestion> labExamQuestionList = labExamQuestionService.list(queryWrapper);

      // Step.3 组装pageList
      List<LabExamQuestionPage> pageList = new ArrayList<LabExamQuestionPage>();
      for (LabExamQuestion main : labExamQuestionList) {
          LabExamQuestionPage vo = new LabExamQuestionPage();
          BeanUtils.copyProperties(main, vo);
          List<LabExamQuestionAnswer> labExamQuestionAnswerList = labExamQuestionAnswerService.selectByMainId(main.getId());
          vo.setLabExamQuestionAnswerList(labExamQuestionAnswerList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "考试试题信息表列表");
      mv.addObject(NormalExcelConstants.CLASS, LabExamQuestionPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("考试试题信息表数据", "导出人:"+sysUser.getRealname(), "考试试题信息表"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
//    @RequiresPermissions("question:lab_exam_question:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          // 获取上传文件对象
          MultipartFile file = entity.getValue();
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<LabExamQuestionPage> list = ExcelImportUtil.importExcel(file.getInputStream(), LabExamQuestionPage.class, params);
              for (LabExamQuestionPage page : list) {
                  LabExamQuestion po = new LabExamQuestion();
                  BeanUtils.copyProperties(page, po);
				  po.setBankId("bankId");
                  labExamQuestionService.saveMain(po, page.getLabExamQuestionAnswerList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

	 /**
	  *  更新导入试题库的题库id
	  *
	  * @param  @RequestParam(name="bankId",required=true) String bankId
	  * @return
	  */
	 @AutoLog(value = "考试试题信息表-更新导入试题库的题库id")
	 @ApiOperation(value="考试试题信息表-更新导入试题库的题库id", notes="考试试题信息表-更新导入试题库的题库id")
	 @DeleteMapping(value = "/updateQuestion")
	 public Result<String> updateQuestion(@RequestParam(name="bank_Id",required=true) String bank_Id) {
		 this.labExamQuestionService.updateQuestion(bank_Id);
		 return Result.OK("更新成功成功！");
	 }



}
